/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bsp.h"
#include "uart_servo_lite.h"
#include "memory.h"
#include "vl53l0x.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint8_t map_to_degrees(uint16_t pos);
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
//舵机旋转角度选择
#define SERVO_DEGREE_0 0
#define SERVO_DEGREE_255 1
//舵机pos值设置上限
#define SERVO_POS_0 100
#define SERVO_POS_255 4000
//中断控制舵机使能
#define SERVO_ENABLE 1
#define SERVO_DISABLE 0
//中断读取数据使能
#define POS_ENABEL 1
#define POS_DISABLE 0
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
//舵机控制初始化
uint8_t sid = 1;							//舵机id
UART_HandleTypeDef* servoUsart = &huart2;	//舵机通信串口
int posAttainCnt = 0;					//舵机角度读取时间 t = posAttainCnt*1ms
int servo_Cnt = 0;						//舵机旋转时间控制 t = servo_Cnt*1ms
int servo_select = SERVO_DEGREE_0;		//舵机旋转角度选择可取SERVO_DEGREE_0与SERVO_DEGREE_0
int servo_Ctr = SERVO_DISABLE;			//中断控制舵机标志位
uint8_t target_deg = 0;

//数据处理初始化
int pos_Ctr = POS_ENABEL;				//中断读取数据标志位
char pos_string[10] = "";				//显示字符串准备
volatile uint16_t pos = 0;				//舵机位置获取
volatile uint8_t pos_deg = 0;			//舵机角度计算

//状态机变量
uint8_t STATE; 							//全局变量状态机
uint8_t DState; 						//跳出循环控制变量
extern uint8_t Serial_RxFlag;
extern uint8_t ByteRecv;
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
	if(huart==&huart1){
		Serial_RxFlag=1;//已接收标志位，说明已经接受完�????????????�????????????
		HAL_UART_Receive_IT(&huart1,&ByteRecv,1);
	}
}

// 角度转舵机控制量（整数运算优化版）
uint16_t angle_to_control(uint8_t angle) {
    // 限制输入范围
    if (angle > 255) angle = 255;

    // 计算公式：control = 105 + angle * (3975 - 105) / 255
    uint16_t control = 105 + (angle * 3870 / 255);

    // 确保结果在有效范围内
    if (control < 105) control = 105;
    else if (control > 3975) control = 3975;

    return control;
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */

  OLED_Init();//OLED初始化
  OLED_Clear();//清屏
  OLED_ShowString(1, 1, "HAL_Init");

  while(vl53l0x_init(&vl53l0x_dev))//vl53l0x初始化
  {
	  HAL_Delay(500);
  }
  //初始化显示
  OLED_Clear(); OLED_ShowString(1, 1, "vl53l0x Init!");

  //显示
  OLED_Clear();            //清屏
  OLED_ShowString(1,1,"VL53L0X Init！");
//  OLED_ShowString(2,6,"mm");
//  OLED_ShowString(3,6,"du");

  //启用默认模式(30ms完成测距)
  vl53l0x_general_Init(&vl53l0x_dev,Default_Mode);

  //串口中断接受
  HAL_UART_Receive_IT(&huart1,&ByteRecv,1);//启动中断接收1byte
  char message1[20]="";
  char message2[20]="";
  char message3[20]="";

  USL_SetServoAngle(servoUsart, sid, 0, 0);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	  switch (STATE) {
	  		case 0:
	  			//待机
	  			DState=0;
	  			while(1){
	  				LCD_SendByte1();
	  				if(DState==1) break;
	  			}
	  			break;

	  		case 1:
	  			//mode1
	  			DState=0;
	  			uint32_t distance1=0;
	  			uint32_t min_distance1=999;//极大值
	  			servo_Ctr = SERVO_ENABLE;	//中断控制舵机使能，开始旋转
	  			HAL_TIM_Base_Start_IT(&htim2);
	  			while(1){
	  				//一次测量
	  				distance1=vl53l0x_general_Measure(&vl53l0x_dev);

//	  				//显示数值
//					OLED_ShowNum(2, 1, distance1, 4);
//					OLED_ShowNum(3, 1, pos_deg, 3);
	  				//距离处理
	  				if(distance1<900&&distance1>0){
	  					if(distance1<min_distance1)
	  						min_distance1=distance1;
	  				}

	  				//串口屏显示
	  				Serial_Printf("x0.val=%d",min_distance1);
					Serial_Send();

					//修改为旋转到头停止
					if(pos_deg > 250){
						servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						DState = 1; STATE = 0;
					}

	  				if(DState==1){
						servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
	  					USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
	  					servo_Cnt = 0;
	  					target_deg = 0;
	  					break;
	  				}
	  				//云台实现基本旋转操作，记得减13（理论值）
	  			}
	  			break;
	  		case 2:
	  			//mode2
	  			DState=0;
	  			int cnt=0;
	  			uint32_t distance2=0;
	  			servo_Ctr = SERVO_ENABLE;	//中断控制舵机失能，停止旋转
	  			HAL_TIM_Base_Start_IT(&htim2);	//中断控制舵机使能，开始旋转
	  			while(1){
	  				distance2=vl53l0x_general_Measure(&vl53l0x_dev);

//	  				//显示
//					OLED_ShowNum(2, 1, distance2, 4);
//					OLED_ShowNum(3, 1, pos_deg, 3);

	  				if(distance2<800 && distance2>0){
	  					cnt++;
	  					while(distance2<800 && distance2>0){distance2=vl53l0x_general_Measure(&vl53l0x_dev);}
	  				}

	  				Serial_Printf("n0.val=%d",cnt);
	  				Serial_Send();

	  				if(pos_deg > 250){
	  					servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						DState = 1; STATE = 0;
	  				}

	  				if(DState==1){
	  					servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						break;
					}
	  			}
	  			break;

	  		case 3:
	  			//mode3
	  			DState=0;
	  			uint32_t distance3=0;
				uint32_t min_distance3=999;//极大值
				uint32_t end_angle3=0; //记录最终确定的角度
				uint32_t mode3_Distance_arr[6]={0}; //存储每个易拉罐和中心点的测量距离
				uint32_t mode3_Angle_arr[6]={0}; //存储每个易拉罐对应的角度
				uint32_t i=0,j=0; //arr数组下标
				uint32_t flag3=0; //标志位
				float mode3_min_distance=0; //两物体间最短距离

				//舵机旋转初始化
				servo_Ctr = SERVO_ENABLE;
				HAL_TIM_Base_Start_IT(&htim2);

	  			while(1){
	  				distance3=vl53l0x_general_Measure(&vl53l0x_dev);

//	  				//显示
//	  				OLED_ShowNum(2, 1, distance3, 4);
//	  				OLED_ShowNum(3, 1, pos_deg, 3);

					if(distance3<800&&distance3>0){
						flag3=1; //检测到易拉罐
						if(distance3<min_distance3)
							min_distance3=distance3;
							end_angle3 = pos_deg;//云台确定实时角度
					}
					if(distance3>800 && flag3==1) {
						flag3=0; // 脱离易拉罐
						mode3_Distance_arr[i++]=min_distance3 + 55 + 54/2; //把最小值存入数组
						mode3_Angle_arr[j++]=end_angle3; //把确定的角度存入数组
						min_distance3=999; //归位
					}
					//云台确定结束一次测量的标志
					//余弦定理计算对边,记得加上易拉罐半径然后最后结果减两个易拉罐半径

					if(pos_deg > 250){
						mode3_min_distance=Calc_mode3_distance(mode3_Distance_arr,mode3_Angle_arr);
	  					servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						DState = 1; STATE = 0;
					}

	  				Serial_Printf("x0.val=%d",(int)mode3_min_distance - 54);
	  				Serial_Send();

	  				if(DState==1){
	  					servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
	  					break;
	  				}
	  				//云台实现记录角度
	  			}
	  			break;
	  		case 4:
	  			//hmode1
	  			DState=0;
	  			uint32_t distance4=0;
	  			uint32_t end_angle4=0; //记录最终确定的角度
	  			uint32_t hmode1_r_θ[2]={0}; //记录极坐标值
	  			uint32_t hmode1_x,hmode1_y=0; //映射到坐标轴上的坐标点
	  			//初始化
	  			servo_Ctr = SERVO_ENABLE;
				HAL_TIM_Base_Start_IT(&htim2);
	  			while(1){
	  				distance4=vl53l0x_general_Measure(&vl53l0x_dev);

//	  				//显示数值
//					OLED_ShowNum(2, 1, min_distance4, 4);
//					OLED_ShowNum(3, 1, end_angle4, 3);

					if(distance4<800&&distance4>0){
						end_angle4 = pos_deg;//云台确定实时角度
						hmode1_x=(int)(172.0f+(8.0f/5.0f)*0.1*distance4*cos(end_angle4*M_PI/180.0f));
						hmode1_y=(int)(134.0f-(8.0f/5.0f)*0.1*distance4*sin(end_angle4*M_PI/180.0f));
						Serial_Printf("cir %d,%d,1,RED",hmode1_x,hmode1_y);
						SendEnd();
					}

	  				LCD_SendByte2();

	  				if(pos_deg > 250){
						servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						DState = 1; STATE = 0;
					}


	  				if(DState==1){
						servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						break;
	  				}
	  			}
	  			break;
	  		case 5:
	  			//hmode2
	  			DState=0;
	  			uint32_t distance5=0;
				uint32_t end_angle5=0; //记录最终确定的角度
				uint32_t hmode2_r_θ[2]={0}; //记录极坐标值
				uint32_t hmode2_x,hmode2_y=0; //映射到坐标轴上的坐标点

				//初始化
				servo_Ctr = SERVO_ENABLE;
				HAL_TIM_Base_Start_IT(&htim2);

	  			while(1){
	  				distance5=vl53l0x_general_Measure(&vl53l0x_dev);

//					//显示数值
//					OLED_ShowNum(2, 1, distance1, 4);
//					OLED_ShowNum(3, 1, pos_deg, 3);


					if(distance5<800&&distance5>0){
						end_angle5 = pos_deg;//云台确定实时角度
						hmode1_x=(int)(172.0f+(8.0f/5.0f)*0.1*distance5*cos(end_angle5*M_PI/180.0f));
						hmode1_y=(int)(134.0f-(8.0f/5.0f)*0.1*distance5*sin(end_angle5*M_PI/180.0f));
						Serial_Printf("cir %d,%d,1,RED",hmode1_x,hmode1_y);
						SendEnd();
					}

	  				LCD_SendByte2();

	  				if(pos_deg > 250){
						servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						DState = 1; STATE = 0;
					}


	  				if(DState==1){
						servo_Ctr = SERVO_DISABLE;	//中断控制舵机失能，停止旋转
						HAL_TIM_Base_Stop_IT(&htim2);
						USL_SetServoAngle(servoUsart, sid, 0, 0);	//舵机归零
						servo_Cnt = 0;
						target_deg = 0;
						break;
	  				}

	  			}
	  			break;
	  }
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
	if(htim == &htim2)
	{
		//TIM2定时器的计数周期为5ms
		//中断控制舵机
		if(servo_Ctr){
			servo_Cnt ++;
			if(servo_Cnt == 7){//每35ms进行一次角度改变
				USL_SetServoAngle(servoUsart, sid, angle_to_control(target_deg), 0);
				target_deg ++;
				servo_Cnt = 0;
			}
		}
		//中断读取数据
		if(pos_Ctr){
			pos = USL_GETPositionVal(servoUsart, sid);
			pos_deg = map_to_degrees(pos);
		}

//		if(STATE == 2 && pos_deg == 255){
//			cnt = 0; //回转时清零，重新计数
//		}

	}
}

//角度转换函数
uint8_t map_to_degrees(uint16_t pos) {
    // 输入范围检查（可选）
    if (pos < 105) return 0;
    if (pos > 3975) return 255;

    // 映射计算
    uint32_t output = (uint32_t)(pos - 105) * 255 / (3975 - 105);
    return (uint8_t)output;
}



/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
